var inputSeries = Math.floor(Math.random()*10+1);
var seriesPage = 1;

//converts plain-text input to thumbnail image code 
function imgEncode( str ){
// encodeURIComponent skips "~!*()'", so we include them here
  if (str.indexOf("|") != -1) {
    str = str.substring(0,str.length -2);
  }
  // fix for IE href attribute
  if ($.browser.msie && str.indexOf("http://" + window.location.hostname) != -1) {
    str = str.replace("http://" + window.location.hostname, "");
    }
  str = str.substring(10);

  //return "thumbnails/" + $.trim(str) + ".gif";
  //return "thumbnails/"+ encodeURIComponent($.trim(str)).replace(/!/g,'%21').replace(/\*/g,'%2A').replace(/\(/g,'%28').replace(/\)/g,'%29').replace(/'/g,'%27') +".gif";
   return "thumbnails/"+ encodeURIComponent($.trim(str)).replace(/!/g,'%21').replace(/\*/g,'%2A').replace(/\(/g,'%28').replace(/\)/g,'%29').replace(/'/g,'%27') +".gif";

}

function loadThumbnails() {
/* load the thumbnail images later in order to keep the front page
      smaller and use progressive enhancement */
   $(".thumbs a").each(function(){
      if ($(this).attr("href") != "") {
        $(this).append('<b class="framed"><img src="'+imgEncode($(this).attr("href"))+'" /><b class="frame"></b></b>');
      }
    });
}

/*--- onload ---*/
$(function(){
   // Experimental domain shifting code
//   $("#calculate").attr("action","http://www.devel"+Math.ceiling(Math.random()*5)+".wolframalpha.com/input/");

    $("#inputs").one("mouseover",loadThumbnails);

    // Start the spinning icon if we are getting more data
    $("#spin").ajaxStart(function(){
        $(this).addClass("active");
        // disable the feedback form
        $("#tmpMessage").attr("disabled","disabled");
    }).ajaxStop(function(){
        $(this).removeClass("active");
        // enable the feedback form
        $("#tmpMessage").attr("disabled","");
    });


 /*if ($.browser.safari) {
    $("#footer ul li").css("padding-right", "14px").css("padding-left", "14px");
    $("#footer ul li:last-child").css("padding-right", "0");
    $("#footer ul li:first-child").css("padding-left", "0");
  }*/ 

  // give focus to the input field if there is no current value for i
  if($("#i").val() === ""){$("#i").focus();}

  /* if scripts are running, we assume the user wants to use asynchronous pods */
  $("input[name='asynchronous']").remove();


    $("#inputs ul.thumbs:last-child li:last-child a").css("color","#db0303");
    $("#tmpMessage").attr("disabled","");

    // Show large image howto
    $("#summary").click(function(e){ e.preventDefault();
     $("body").append('<div id="about"><div class="popup"><a alt="close" class="close" href="/">close<img src="/images/close-home-popup.png" /></a><img src="/images/home-popup.png" height="694" width="734" /></div></div>');
      $("#about").show();
      $("#about").click(function(e){e.preventDefault(); $("#about").hide();});
    });

    $("#inputs").click(function(e){
      if($(e.target).text().indexOf("more") == 0) {
        e.preventDefault();
        seriesPage>= 6?1:seriesPage++;
        $("#inputs").load("/inputs/sampleinputs"+inputSeries+"-"+seriesPage+".htm",function(){
          $("#inputs").prepend('<h2><a href="/examples/">Sample Inputs</a></h2>').css("display","block").css("display","");
          loadThumbnails();
        });
        if (seriesPage == 6) {
           $("#inputs").click(function(e){
             if($(e.target).text().indexOf("more") == 0) {
               e.preventDefault();
                window.open("/examples/","examples");
             }
           });
        }
      }
    });

     $("#calculate").submit(function(e){
        // if the input is blank, go home
        if ($("#i").val().replace(/\s*/g,"")=="") {
            e.preventDefault();
                window.location = "/";
                return;
        }
    // Load the animated GIF image
    $("#spin").addClass("active");

    // Hide the previous calculation's results and footer
    $("#warnings,.assuming,.popup,#results,#timeout,#sources,#footer,#debug-wrapper,#sidebar,#splat,#ex-main-content,#related").hide();
    }).keypress(function(e){
        if(e.which == 13){$("#calculate").submit();}
  });

  $("div#equal").click(function(){
    $("#calculate").submit();
  });

/* Feedbback */
    // load the feedback form only when needed
    $("#feedback").bind("focus keyup click",function(e){
      if ($(e.target).is("#tmpMessage,#tmpSend,#giveus")){
        var val = this.value;
        $("#feedback").load("/input/feedback.jsp",function(){
        $("#feedback").addClass("open");$("#feedback-textarea").val(val?val:'').focus(); $("#spin").removeClass("active");
        });
      }
    });

    // on submit, load the response page as a pod rather than leave
    $("#feedback").submit(function(e){
      e.preventDefault();

     if ($("#Email").val() == "") {
        emailConfirm();
     }
     else {
      if ($("#Remember").is(":checked")) {
        $.cookie('WolframAlphaName',$("#Name").val(),{expires: 90});
        $.cookie('WolframAlphaEmail',$("#Email").val(),{expires: 90});
        $.cookie('WolframAlphaOccupation',$("#Occupation").val(),{expires: 90});
        $.cookie('WolframAlphaOrganization',$("#Organization").val(),{expires: 90});
        $.cookie('WolframAlphaCountry',$("#Country").val(),{expires: 90});
     }

     $("#feedback hr.top,#feedback hr.bot, #feedback table").css("display","none");  
     $("#ec").remove();
     $("#feedback").append('<div style="height:150px;">&nbsp;</div>');
     var data = $("#feedback").serializeArray();
     $("#feedback").load("/input/sendmessage.jsp #thanks",data,  function(){
        $("#thanks .close").click(function(){$(this).parent().remove();});
        $("#feedback").append("<fieldset></fieldset>");
        $("#feedback fieldset").load("/input/footer.jsp fieldset *", {i:"i"});
     }).removeClass("open");
      return true;
    }
  });

/* ------------------------------------- */
  if ($.browser.opera) {
    $("#sidebar").css("margin-top", "47px");
  } else if ($.browser.safari) {
    $("#sidebar").css("margin-top", "47px");
  }

  if ($.browser.safari) {
    $("#footer ul li").css({"padding-right": "21px","padding-left":"21px"});
    $("#footer ul li:last-child").css("padding-right", "0");
    $("#footer ul li:first-child").css("padding-left", "0");
  }

  var newto = true;

if ($.browser.msie) {
  $("#inputArrow").attr("src", "http://" + window.location.hostname + "images/newtoalpha-inputarrow-ie.gif");
}

if (newto && $.cookie('new_to_alpha') == null) {
  loadNewToAlpha();
 } else {
  if (newto) {
    $.cookie('new_to_alpha', 'hide', {domain: '.wolframalpha.com'});
  }
  $("#newToAlphaContainer").remove();
  $("#sidebar").css("left", "auto");
}
        

});

var removeArrow;
var arrow;

function loadNewToAlpha() {
  $.cookie('new_to_alpha', null, {domain: '.wolframalpha.com'});
  
  if ($("#newToAlphaContainer").length == 0){
    $("#sidebar").prepend("<div id=\"newToAlphaContainer\"></div>");
  }
  $("#newToAlphaContainer").load("/newbie.html", function() {
    $("#input").prepend('<img id="inputArrow" style="display: none;"src="/images/newtoalpha-inputarrow.png" alt="Input Arrow" title="Input Arrow" /><img id="howTo" style="display: none;" src="/images/newtoalpha-enterpopup.png" alt="How to Compute" title="How to Compute" />');
    $("#try li a:not(#trymore)").click(function(e) {
      e.preventDefault();
      $("#i").val($(this).find("kbd").html()).focus();
      $("#howTo").css("display", "block");
      $("#inputArrow").css("display", "block");
      if (arrow != null) {
        $("#inputArrow").stop();
        clearTimeout(arrow);
      }
      removeArrow = function() { $("#inputArrow").fadeOut('slow'); }
      arrow = setTimeout(removeArrow, 3000);
    });

    $("#trymore").toggle(function() { // shows more examples to try
      $("#try li.collapse").removeClass("hide");
      $(this).html("less &raquo;");
      // Fixes a bug in IE where the bottom border won't render in the appropriate place
      if ($.browser.msie && $.browser.version == "7.0") {
        $("#newbie .bot").css("top", "0");
        $("#newbie .bot").css("top", "auto");
      }
    },function() {// shows less examples to try
        $("#try li.collapse").addClass("hide");
        $(this).html("more &raquo;");
        // Fixes a bug in IE where the bottom border won't render in the appropriate place
        if ($.browser.msie && $.browser.version == "7.0") {
          $("#newbie .bot").css("top", "0");
          $("#newbie .bot").css("top", "auto");
        }
      });
    $("#newbie h2 > span").hover(function() {
      if ($(this).html() != "") {
        $("#closePopup").removeClass("hide");
      } else {
        $(this).html('<span id="closePopup">Click to close pod.<span>Use <b>MORE</b> &raquo; from the top bar to reopen.</span></span>');
      }
    }, function() {
      $("#closePopup").addClass("hide");
    });
    $("#newbie h2 > span").click(function() {
        $("#newToAlphaContainer").remove();
        $("#relatedlinks, #searchtheweb, #ads").css("top", "").css("top", "auto");
        $.cookie('new_to_alpha', 'hide', {domain: '.wolframalpha.com'});//, { expires: 90 });
      });
      $("#relatedlinks, #searchtheweb, #ads").css("top", "").css("top", "auto");
      $("#sidebar").css("left", "auto");
    });
}

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 */
/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

var parsedExpr = '';
var assumptionsMade = '{}';
var rawAssumptions = '{}';

function emailConfirm(){
  $('#popanchor').append('<div id="ec"> <p>Please include a valid email address if you want to make a response possible.</p> <div> <input id="eci" type="text" /> <input id="ecSend" type="image" src="/images/calculate-feedbackopen-send.gif"/> <br/> <span>We will keep you email address private.</span> </div> <p><b>Send without a return email address &raquo;</b></p></div>');

  /*find position of 'parent' which is the results pod clicked*/
  var pos = $('#fbsb').offset();

  $('#ec').css('top',pos.top-95);
  $('#ec').css('left',pos.left-210);

  $("#ecSend").click(function(e){
    if($("#eci").val() != "" ){
      $("#Email").val($("#eci").val());
      $("#feedback").submit();
    }
  });
  $("#ec b").click(function(e){
    $("#Email").val("Anonymous");   
    $("#feedback").submit();
  });
}

